package org.xs.web.http.provider.servlet;

import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;

import org.xs.web.http.provider.HTTPContext;
import org.xs.web.util.Resources;

public class HTTPServletContext implements HTTPContext{
	private ServletContext servletContext;
	
	public HTTPServletContext(ServletContext context){
		servletContext = context;
	}
	
	@Override
	public Object attribute(String key) {
		return servletContext.getAttribute(key);
	}

	@Override
	public Map<String, Object> attributes() {
		Enumeration<String> names = servletContext.getAttributeNames();
		Map<String, Object> resuts = new HashMap<String, Object>();
		while(names.hasMoreElements()){
			String name = names.nextElement();
			resuts.put(name, attribute(name));
		}
		return Collections.unmodifiableMap(resuts);
	}

	@Override
	public String contentPath() {
		return servletContext.getContextPath();
	}

	@Override
	public ServletContext getDelegate() {
		return servletContext;
	}

	@Override
	public String initParam(String name) {
		return servletContext.getInitParameter(name);
	}

	@Override
	public List<String> initParams() {
		List<String> result = new ArrayList<String>();
		Enumeration<String> names = servletContext.getInitParameterNames();
		while(names.hasMoreElements()){
			result.add(servletContext.getInitParameter(names.nextElement()));
		}
		return Collections.unmodifiableList(result);
	}

	@Override
	public String path() {
		return contentPath();
	}

	@Override
	public Object removeAttribute(String key) {
		Object res = servletContext.getAttribute(key);
		servletContext.removeAttribute(key);
		return res;
	}

	@Override
	public URL resource(String path) {
		try {
			return servletContext.getResource(path);
		} catch (MalformedURLException e) {
			 
		}
		return null;
	}

	@Override
	public InputStream resourceAsStream(String path) {
		return Resources.getResourceAsStream(path, servletContext);
	}

	@Override
	public Object setAttribute(String key, Object value) {
		Object res = attribute(key);
		servletContext.setAttribute(key, value);
		return res;
	}

	@Override
	public String mimeType(String file) {
		return servletContext.getMimeType(file);
	}

	@Override
	public String serverInfo() {
		return servletContext.getServerInfo();
	}

}
